﻿using AuthCenter_HuangJingtao.Domain;
using AuthCenter_HuangJingtao.ErrorCode;
using AuthCenter_HuangJingtao.Infrastructure.Imterfaces;
using AuthCenter_HuangJingtao.Read.Api.Application.Command;
using MediatR;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace AuthCenter_HuangJingtao.Read.Api.Application.CommandHandler
{
    public class AddGroupShipCommandHandler : IRequestHandler<AddGroupShipCommand, ApiResult<int>>
    {
        IBaseReponsitory<Roles> Roles;
        IBaseReponsitory<App> Apps;
        IBaseReponsitory<RoleApp> RoleApp;

        public AddGroupShipCommandHandler(IBaseReponsitory<Roles> Roles, IBaseReponsitory<App> Apps, IBaseReponsitory<RoleApp> RoleApp)
        {
            this.Roles = Roles;
            this.Apps = Apps;
            this.RoleApp = RoleApp;
        }

        public async Task<ApiResult<int>> Handle(AddGroupShipCommand request, CancellationToken cancellationToken)
        {
            var data = request.App_Id;
            //把request.App_Id的值[1,2,3]转换成int []并且做循环
            int[] app_ids = data.Split(',').Select(int.Parse).ToArray();
            //循环每一个app_id
            foreach (int app_id in app_ids)
            {
                var app = Apps.GetQuery().Where(c => c.App_Id == app_id).FirstOrDefault();//选择
                var arr = app.Role_ArrId.Split(',').Select(int.Parse).ToArray();
                foreach (int role_id in arr)
                {
                    if (role_id == request.Role_Id){ }
                    else 
                    {
                        //添加新的role_id到[1,2,3]以,隔开
                        app.Role_ArrId=string.Join(",", arr) + "," + request.Role_Id;
                        app.Role_ArrId= app.Role_ArrId.TrimEnd('、');
                        await Apps.UpdateAsync(app);
                    }
                }
            }

            return new ApiResult<int>
            {
                Code = ApiEnum.Success,
                Message = "保存成功",
                Data = 1

            };

        }
    }
}
